package com.five.matebook.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.five.matebook.R;
import com.five.matebook.activity.columeedit.CustomValueManager;
import com.five.matebook.activity.config.StroageConfig;
import com.five.matebook.activity.db.OneQueryData;
import com.five.matebook.activity.db.QueryFilter;
import com.five.matebook.activity.db.TableBase;
import com.five.matebook.utils.DateUtils;
import com.five.matebook.utils.StringTreeParser;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public abstract class BaseRecordActivity extends FragmentActivity {

    protected void handleIntent(TableBase table) {
        if (getIntent() != null && getIntent().hasExtra("id")) {
            long id = getIntent().getLongExtra("id", -1);
            if (id < 0) {
                Toast.makeText(this, "记录id异常", Toast.LENGTH_SHORT).show();
                this.finish();
            } else {
                QueryFilter filter = new QueryFilter.Builder()
                        .addLongRange("id", id, id)
                        .build();
                List<OneQueryData> list = table.query(filter);
                if (list.size() > 0) {
                    mOldData = list.get(0);
                } else {
                    Toast.makeText(this, "记录id不能存在", Toast.LENGTH_SHORT).show();
                }
                mEditable = false;  // 打开老记录时，默认是查看模式
            }
        }
    }

    protected float getTextviewValue(TextView v, float def) {
        String x = v.getText().toString();
        if (TextUtils.isEmpty(x)) {
            return def;
        }
        try {
            return Float.parseFloat(x);
        } catch (Exception e) {
            return def;
        }
    }

    protected String getSpinnerValue(Spinner spinner) {
        Object obj = spinner.getSelectedItem();
        if (obj == null) {
            return "";
        }
        return String.valueOf(obj);
    }

    protected int setSpinnerText(Spinner spinner, int index) {
        AdapterView.OnItemSelectedListener old = spinner.getOnItemSelectedListener();
        spinner.setOnItemSelectedListener(null);
        if (index >=0 && index < spinner.getCount()) {
            spinner.setSelection(index, false);
        }
        spinner.setOnItemSelectedListener(old);
        return index;
    }

    protected int setSpinnerText(Spinner spinner, String text) {
        return setSpinnerText(spinner, text, true);
    }
    protected int setSpinnerText(Spinner spinner, String text, boolean disableItemSelect) {
        int index = -1;
        AdapterView.OnItemSelectedListener old = spinner.getOnItemSelectedListener();
        if (disableItemSelect) {
            spinner.setOnItemSelectedListener(null);
        }
        if(spinner.getAdapter() != null) {
            for (int i = 0; i < spinner.getAdapter().getCount(); i++) {
                String obj = spinner.getAdapter().getItem(i).toString();
                if (obj.equals(text)) {
                    spinner.setSelection(i, false);
                    index = i;
                    break;
                }
            }
        }

        if (!TextUtils.isEmpty(text) && index < 0) {
            // 设置的内容不为空，但是在列表中没有找到，可能是删除了。。
            spinner.setTag(R.integer.spinner_old_list, spinner.getAdapter());
            List<String> tmp = new ArrayList<>();
            tmp.add(text);
            spinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, tmp));
        }

        if (disableItemSelect) {
            spinner.setOnItemSelectedListener(old);
        }
        return index;
    }

    protected void setChildsEnable(ViewGroup parent, boolean enable) {
        for (int i=0; i< parent.getChildCount(); i++) {
            View v = parent.getChildAt(i);

            if (v instanceof Spinner) {
                if (enable) {
                    AdapterView.OnItemSelectedListener old = (AdapterView.OnItemSelectedListener) v.getTag();
                    if (old != null) {
                        ((Spinner) v).setOnItemSelectedListener(old);
                    }
                    Object obj = v.getTag(R.integer.spinner_old_list);
                    if (obj != null) {
                        ((Spinner) v).setAdapter((SpinnerAdapter)obj);
                    }
                } else {
                    AdapterView.OnItemSelectedListener old = ((Spinner)v).getOnItemSelectedListener();
                    v.setTag(old);
                    ((Spinner)v).setOnItemSelectedListener(null);
                }
                v.setEnabled(enable);
            } else if (v instanceof ViewGroup) {
                setChildsEnable((ViewGroup) v, enable);
            } else {
                if (v instanceof Button) {

                } else {
                    v.setEnabled(enable);
                }
            }
        }
    }

    protected <T> ArrayAdapter<T> generateSpinnerAdapter(List<T> list) {
        ArrayAdapter ret = new ArrayAdapter<>(getApplicationContext(), R.layout.spinner_layout, list);
        ret.setDropDownViewResource(R.layout.spinner_dropdown);
        return ret;
    }

    protected boolean mEditable = true;
    protected OneQueryData mOldData;
    protected RecordForm mRecordForm;

    protected ViewGroup mRootView = null;
    protected TextView mTxtTitle;

    protected Button mButEdit;
    protected Button mButSubmit;
    protected Button mButNewRecord;

    protected void setRecordForm(RecordForm recordForm) {
        this.mRecordForm = recordForm;

        this.mRootView = findViewById(R.id.root);
        this.mTxtTitle = findViewById(R.id.txt_title);

        this.mButEdit = findViewById(R.id.but_edit);
        this.mButSubmit = findViewById(R.id.but_submit);
        this.mButNewRecord = findViewById(R.id.but_new_record);
    }

    public void onSubmitClick(View v) {
        OneQueryData data = this.mRecordForm.submit(mOldData != null ? mOldData.getLong("id", 0) : null);
        if (data != null) {
            mOldData = data;
            mEditable = false;
            updateUi();
        } else {

        }
    }

    public void onEditButClick(View v) {
        if (StroageConfig.get(this).isAdmin()) {
            Toast.makeText(this, "管理员不能编辑，只能查看哟", Toast.LENGTH_SHORT).show();
            return;
        }
        mEditable = true;
        updateUi();
    }

    /**新纪录一笔
     * @param v
     */
    public void onNewRecordButClick(View v) {
        if (StroageConfig.get(this).isAdmin()) {
            Toast.makeText(this, "管理员不能新增，只能查看哟", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, this.getClass());
        startActivity(intent);
        this.finish();
    }

    protected void updateUi() {
        updateChildUi();
        setChildsEnable(mRootView, mEditable);
    }

    protected void setTime2TextView(TextView v, long time) {
        setTime2TextView(v, time, false);
    }
    protected void setTime2TextView(TextView v, long time, boolean dateOnly) {
        v.setText(DateUtils.toString(time, dateOnly));
        v.setTag(time);
    }

    protected long getTimeFromTextView(TextView v) {
        return (long) v.getTag();
    }

    protected StringTreeParser getStringTreeParser(String filed, int resId, int level) {
        List<String> customList = CustomValueManager.getInstance(getApplicationContext()).getFiledValues(filed);
        return new StringTreeParser(this, customList, resId, level);
    }

    protected void showAlert(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(BaseRecordActivity.this)
                        .setTitle("提示")
                        .setMessage(msg)
                        .setCancelable(false)
                        .setPositiveButton("我知道了", null)
                        .show();
            }
        });
    }

    abstract protected void updateChildUi();
}
